package com.wei.web.middleware.httpfilter.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.wei.web.middleware.httpfilter.enums.ErrorEnum;
import com.wei.web.middleware.httpfilter.exceptions.FASException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;

import java.io.IOException;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseWrapper<T> {

    private boolean status = true;
    private String errorCode;
    private String errorMessage;

    @JsonIgnore
    private String desensitizeStatus = "false";

    private T result;

    public static<T> ResponseWrapper<T> success() {
        ResponseWrapper<T> response = new ResponseWrapper<>();
        response.setStatus(true);
        return response;
    }

    public static<T> ResponseWrapper<T> successDesensitize(T result) {
        ResponseWrapper<T> response = new ResponseWrapper<>();
        response.setStatus(true);
        response.setDesensitizeStatus("true");
        response.setResult(result);
        return response;
    }

    public static<T> ResponseWrapper<T> success(T result) {
        ResponseWrapper<T> response = new ResponseWrapper<>();
        response.setStatus(true);
        response.setResult(result);
        return response;
    }


    /**
     * Must not be public, error code should be maintained in ErrorEnum
     */
    private static<T> ResponseWrapper<T> error(final int errorCode, final String errorMessage) {
        ResponseWrapper<T> response = new ResponseWrapper<>();
        response.setStatus(false);
        response.setErrorCode(String.valueOf(errorCode));
        response.setErrorMessage(errorMessage);
        return response;
    }

    /**
     * Must not be public, error code should be maintained in ErrorEnum
     */
    private static<T> ResponseWrapper<T> error(ErrorEnum errorEnum) {
        ResponseWrapper<T> response = new ResponseWrapper<>();
        response.setStatus(false);
        response.setErrorCode(String.valueOf(errorEnum.getCode()));
        response.setErrorMessage(errorEnum.getMessage());
        return response;
    }

    public static<T> void responseError(ErrorEnum errorEnum, HttpServletResponse response) {
        try {
            ResponseWrapper<T> responseWrapper = ResponseWrapper.error(errorEnum);
            String strResponseWrapper = JSONObject.toJSONString(responseWrapper);
            response.setHeader("Content-Type", "application/json");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(strResponseWrapper);
        } catch (IOException e) {
            throw new FASException(ErrorEnum.UNKNOWN_ERROR);
        }
    }

}
